<?php
namespace app\common\model;

use think\facade\Db;
use think\facade\Request;
use think\Model;
use think\model\concern\SoftDelete;

class UserRecharge extends Model
{
    use SoftDelete;
    protected $pk                = 'recharge_id';
    protected $deleteTime        = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $type              = [
        'create_time' => 'timestamp',
        'update_time' => 'timestamp',
        'out_time'    => 'timestamp',
        'pay_time'    => 'timestamp',
    ];

    public static function onBeforeInsert($data)
    {

        $data->recharge_id = date('YmdHis') . random(16, 1);
        $data->create_time = Request::time();
        $data->create_ip   = Request::ip();
        $data->out_time    = Request::time() + 86400;
        $data->status      = 0;
    }

    public function getStatusTextAttr($value, $data)
    {
        switch ($data['status']) {
            case -1:
                return '已失效';
                break;
            case 0:
                return '待支付';
                break;
            case 1:
                return '已完成';
                break;

            default:
                return '未知';
                break;
        }
    }

    public function getTextColorAttr($value, $data)
    {
        switch ($data['status']) {
            case -1:
                return 'text-danger';
                break;
            case 0:
                return 'text-info';
                break;
            case 1:
                return 'text-success';
                break;

            default:
                return 'text-secondary';
                break;
        }
    }

    public function getPayTypeAttr($value, $data)
    {
        if (empty($data['payinfo'])) {
            return '未支付';
        }

        $payinfo = json_decode($data['payinfo'], true);
        if (!empty($payinfo['openid'])) {
            return '微信支付';
        }
        if (!empty($payinfo['alipay_trade_query_response'])) {
            return '支付宝';
        }
        if (!empty($payinfo['retmsg'])) {
            return 'QQ钱包';
        }
    }

    public function goPay($payment)
    {
        global $_G;
        $data = [
            'trade_type' => 'NATIVE',
            'order_id'   => $this->recharge_id,
            'price'      => round($this->price, 2),
            'subject'    => $this->subject,
            'body'       => $this->body,
        ];
        if ($payment == 'alipay') {
            if (!$_G['setting']['alipay_switch']) {
                return ['code' => 0, 'msg' => '暂未开放支付宝在线充值'];
            }
            return (new \payment\Alipay)
                ->setConfig([
                    'notify_url' => url('index/notify/alipay', [], false, true),
                ])
                ->setOrder($data)
                ->unifiedOrder();
        } else if ($payment == 'wxpay') {
            if (!$_G['setting']['wxpay_switch']) {
                return ['code' => 0, 'msg' => '暂未开放微信支付在线充值'];
            }
            $result = (new \payment\Wxpay)
                ->setConfig([
                    'notify_url' => url('index/notify/wxpay', [], false, true),
                ])
                ->setOrder($data)
                ->unifiedOrder();
            if (empty($result['code_url'])) {
                return ['code' => 0, 'msg' => '生成二维码失败，请重试'];
            }
            return ['code' => 1, 'msg' => '请使用微信扫码完成支付', 'qrcode' => $result['code_url']];
        } else if ($payment == 'qqpay') {
            if (!$_G['setting']['qqpay_switch']) {
                return ['code' => 0, 'msg' => '暂未开放QQ钱包在线充值'];
            }
            $result = (new \payment\Qqpay)
                ->setConfig([
                    'notify_url' => url('index/notify/qqpay', [], false, true),
                ])
                ->setOrder($data)
                ->unifiedOrder();
            if (empty($result['code_url'])) {
                return ['code' => 0, 'msg' => '生成二维码失败，请重试'];
            }
            return ['code' => 1, 'msg' => '请使用QQ扫码完成支付', 'qrcode' => $result['code_url']];
        }
        return ['code' => 0, 'msg' => '请选择正确的支付通道'];
    }

    public function query()
    {
        global $_G;
        $payinfo = false;
        if ($_G['setting']['alipay_switch']) {
            $result = (new \payment\Alipay)->setOrder(['order_id' => $this->getAttr('recharge_id')])->queryOrder();
            if (!empty($result['transaction_id']) && $this->getAttr('status') !== 1) {
                $payinfo = $result;
            }
        }
        if ($_G['setting']['wxpay_switch'] && $payinfo === false) {
            $result = (new \payment\Wxpay)->setOrder(['order_id' => $this->getAttr('recharge_id')])->queryOrder();
            if (!empty($result['transaction_id']) && $this->getAttr('status') !== 1) {
                $payinfo = $result;
            }
        }
        if ($_G['setting']['qqpay_switch'] && $payinfo === false) {
            $result = (new \payment\Qqpay)->setOrder(['order_id' => $this->getAttr('recharge_id')])->queryOrder();
            if (!empty($result['transaction_id']) && $this->getAttr('status') !== 1) {
                $payinfo = $result;
            }
        }
        if ($payinfo !== false) {
            $this->status      = 1;
            $this->update_time = Request::time();
            $this->pay_time    = Request::time();
            $this->payinfo     = json_encode($payinfo);
            $this->save();
            UserMain::where('uid', '=', $this->getAttr('uid'))->update([
                'balance' => Db::raw('balance+' . $this->getAttr('price')),
            ]);
        }
        return $payinfo;
    }

    public function user()
    {
        return $this->belongsTo(UserMain::class, 'uid');
    }
}
